package com.chenfan.common.extension.mybatisplus.interceptor;

import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.chenfan.common.extension.context.TraceContextHolder;
import com.chenfan.common.extension.context.UserContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.Objects;

/**
 * 默认租户隔离
 * @author wulg
 * @date 2024/3/13
 */
public class DefaultTenantIsolationHandler implements TenantLineHandler {

    private static final String TENANT_ID = "tenant_id";

    @Override
    public final Expression getTenantId() {
        return new LongValue(UserContextHolder.defaultTenantId());
    }

    @Override
    public String getTenantIdColumn() {
        return TENANT_ID;
    }

    @Override
    public boolean ignoreTable(String tableName) {
        if (TraceContextHolder.isFormJob() && Objects.isNull(UserContextHolder.getTenantId())) {
            return true;
        }
        return !TableInfoHelper.getTableInfos().stream().filter(tableInfo -> {
            if (!tableInfo.getTableName().equalsIgnoreCase(tableName)) {
                return false;
            }
            return tableInfo.getFieldList().stream().filter(f -> getTenantIdColumn().equalsIgnoreCase(f.getColumn())).findFirst().isPresent();
        }).findFirst().isPresent();
    }
}
